package com.aipartner.controller;

import com.aipartner.common.Result;
import com.aipartner.entity.CreditsTransaction;
import com.aipartner.entity.CreditsPackage;
import com.aipartner.entity.CreditsOrder;
import com.aipartner.service.CreditsService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.aipartner.util.UserContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 积分系统控制器
 *
 * @author AI Partner
 * @since 2025-09-18
 */
@Api(tags = "积分系统")
@Slf4j
@RestController
@RequestMapping("/api/credits")
public class CreditsController {

    @Autowired
    private CreditsService creditsService;

    /**
     * 获取用户积分信息
     */
    @ApiOperation("获取用户积分信息")
    @GetMapping("/info")
    public Result<Map<String, Object>> getCreditsInfo(HttpServletRequest request) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("用户未登录");
            }

            Map<String, Object> creditsInfo = creditsService.getUserCreditsInfo(userId);
            if (creditsInfo == null) {
                return Result.fail("获取积分信息失败");
            }

            return Result.success(creditsInfo);
        } catch (Exception e) {
            log.error("获取积分信息失败", e);
            return Result.fail("获取积分信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户积分交易记录
     */
    @ApiOperation("获取用户积分交易记录")
    @GetMapping("/history")
    public Result<IPage<CreditsTransaction>> getCreditsHistory(HttpServletRequest request,
                                                               @RequestParam(defaultValue = "1") Integer current,
                                                               @RequestParam(defaultValue = "20") Integer size) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("用户未登录");
            }

            Page<CreditsTransaction> page = new Page<>(current, size);
            IPage<CreditsTransaction> history = creditsService.getUserCreditsHistory(userId, page);
            return Result.success(history);
        } catch (Exception e) {
            log.error("获取积分交易记录失败", e);
            return Result.fail("获取积分交易记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取积分套餐列表
     */
    @ApiOperation("获取积分套餐列表")
    @GetMapping("/packages")
    public Result<List<CreditsPackage>> getCreditsPackages() {
        try {
            List<CreditsPackage> packages = creditsService.getCreditsPackages();
            return Result.success(packages);
        } catch (Exception e) {
            log.error("获取积分套餐失败", e);
            return Result.fail("获取积分套餐失败：" + e.getMessage());
        }
    }

    /**
     * 创建积分购买订单
     */
    @ApiOperation("创建积分购买订单")
    @PostMapping("/orders")
    public Result<CreditsOrder> createCreditsOrder(HttpServletRequest request,
                                                   @RequestBody Map<String, Object> params) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("用户未登录");
            }

            Long packageId = Long.valueOf(params.get("packageId").toString());
            String paymentMethod = params.get("paymentMethod").toString();

            CreditsOrder order = creditsService.createCreditsOrder(userId, packageId, paymentMethod);
            return Result.success(order);
        } catch (Exception e) {
            log.error("创建积分订单失败", e);
            return Result.fail("创建积分订单失败：" + e.getMessage());
        }
    }

    /**
     * 积分购买支付回调处理
     */
    @ApiOperation("积分购买支付回调处理")
    @PostMapping("/payment/callback")
    public Result<Boolean> handlePaymentCallback(@RequestBody Map<String, Object> params) {
        try {
            String orderNo = params.get("orderNo").toString();
            String transactionId = params.getOrDefault("transactionId", "").toString();

            boolean result = creditsService.processCreditsPaymentSuccess(orderNo, transactionId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("处理积分购买回调失败", e);
            return Result.fail("处理支付回调失败：" + e.getMessage());
        }
    }

    /**
     * 获取积分消耗规则
     */
    @ApiOperation("获取积分消耗规则")
    @GetMapping("/consumption/rules")
    public Result<List<Map<String, Object>>> getConsumptionRules() {
        try {
            List<Map<String, Object>> rules = creditsService.getCreditsConsumptionRules();
            return Result.success(rules);
        } catch (Exception e) {
            log.error("获取积分消耗规则失败", e);
            return Result.fail("获取积分消耗规则失败：" + e.getMessage());
        }
    }

    /**
     * 检查积分是否足够
     */
    @ApiOperation("检查积分是否足够")
    @GetMapping("/check")
    public Result<Boolean> checkCreditsEnough(HttpServletRequest request,
                                              @RequestParam Long amount) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("用户未登录");
            }

            boolean enough = creditsService.checkCreditsEnough(userId, amount);
            return Result.success(enough);
        } catch (Exception e) {
            log.error("检查积分失败", e);
            return Result.fail("检查积分失败：" + e.getMessage());
        }
    }

    // ==================== 开发测试接口 ====================
    
    /**
     * 开发测试：添加测试积分
     * 注意：此接口仅供开发测试使用，生产环境请删除！
     */
    @ApiOperation("开发测试：添加测试积分")
    @PostMapping("/dev/add-test-credits")
    public Result<Boolean> addTestCredits(HttpServletRequest request,
                                          @RequestParam(defaultValue = "1000") Long amount) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("用户未登录");
            }

            // 为用户添加测试积分
            String testOrderNo = "DEV_TEST_" + System.currentTimeMillis();
            boolean result = creditsService.addCredits(userId, amount, "dev_test", testOrderNo, "开发测试充值" + amount + "积分");

            return Result.success(result);
        } catch (Exception e) {
            log.error("添加测试积分失败", e);
            return Result.fail("添加测试积分失败：" + e.getMessage());
        }
    }

    /**
     * 开发测试：重置用户积分
     * 注意：此接口仅供开发测试使用，生产环境请删除！
     */
    @ApiOperation("开发测试：重置用户积分")
    @PostMapping("/dev/reset-credits")
    public Result<Boolean> resetCredits(HttpServletRequest request,
                                        @RequestParam(defaultValue = "0") Long amount) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("用户未登录");
            }

            // 重置用户积分
            boolean result = creditsService.resetUserCredits(userId, amount);
            log.info("开发测试：重置用户{}的积分为{}, 结果: {}", userId, amount, result);
            return Result.success(result);
        } catch (Exception e) {
            log.error("重置积分失败", e);
            return Result.fail("重置积分失败：" + e.getMessage());
        }
    }
}
